# Required packages
require(quantreg)
require(tidyverse)
require(tidymodels)
require(ggthemes)

# Version used
# quantreg_5.94

# Load data
load("01_Data/spatial_dimension_data.Rdata")

#### 1-  Quantile regression ####

quant_reg <- rq(delay ~ 
                  time +
                  risk_factor,
                data=model_base,
                tau = seq(0.2, .8, .01))

#### 2 - Figure  A7: Coefficient estimates from quantile regression ####
tidy_quant <- tidy(quant_reg)
tidy_quant$term[tidy_quant$term == "time"] <- "Distance (hours)"
tidy_quant$term[tidy_quant$term == "risk_factorhigh"] <- "Risk (high)"
tidy_quant$term[tidy_quant$term == "risk_factormedium"] <- "Risk (medium)"


pdf("02_Figures/appendix_A7.pdf", height=5, width=10)
tidy_quant %>% 
  filter(term == "Distance (hours)" |
           term == "Risk (high)" |
           term == "Risk (medium)") %>% 
  ggplot(aes(x=tau,y=estimate, ymax=conf.high, ymin=conf.low))+
  geom_linerange(alpha=1, color="grey70",size=.5)+
  geom_point(alpha=1, color="grey30",size=.7)+
  geom_hline(yintercept=0, linetype = 2, alpha=0.2)+
  facet_wrap(~term, scales = "free") +
  theme_base()+
  theme(plot.background = element_blank())+
  ylab("Coefficient")+
  xlab(expression(tau))
dev.off()

rm(list = ls())
